import * as fs from 'fs-extra';
import { join } from 'path';
import { v4 } from 'uuid';

export const copyBaseApplicationProject = async ({
  appName,
  appDisplayName,
  appDescription,
  appDirectory,
}: {
  appName: string;
  appDisplayName: string;
  appDescription: string;
  appDirectory: string;
}) => {
  await fs.copy(join(__dirname, './constants/base-application'), appDirectory);

  await createPackageJson({ appName, appDirectory });

  await createGitignore(appDirectory);

  await createYarnLock(appDirectory);

  await createApplicationConfig({
    displayName: appDisplayName,
    description: appDescription,
    appDirectory,
  });
};

const createYarnLock = async (appDirectory: string) => {
  const yarnLockContent = `# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.
# yarn lockfile v1
`;

  await fs.writeFile(join(appDirectory, 'yarn.lock'), yarnLockContent);
};
const createGitignore = async (appDirectory: string) => {
  const gitignoreContent = `# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.

# dependencies
/node_modules
/.pnp
.pnp.*
.yarn

# codegen
generated

# testing
/coverage

# dev
/dist/

# production
/build

# misc
.DS_Store
*.pem

# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*
.pnpm-debug.log*

# env files (can opt-in for committing if needed)
.env*

# typescript
*.tsbuildinfo
`;

  await fs.writeFile(join(appDirectory, '.gitignore'), gitignoreContent);
};

const createApplicationConfig = async ({
  displayName,
  description,
  appDirectory,
}: {
  displayName: string;
  description?: string;
  appDirectory: string;
}) => {
  const content = `import { type ApplicationConfig } from 'twenty-sdk';

const config: ApplicationConfig = {
  universalIdentifier: '${v4()}',
  displayName: '${displayName}',
  description: '${description ?? ''}',
};

export default config;
`;

  await fs.writeFile(join(appDirectory, 'application.config.ts'), content);
};

const createPackageJson = async ({
  appName,
  appDirectory,
}: {
  appName: string;
  appDirectory: string;
}) => {
  const packageJson = {
    name: appName,
    version: '0.1.0',
    license: 'MIT',
    engines: {
      node: '^24.5.0',
      npm: 'please-use-yarn',
      yarn: '>=4.0.2',
    },
    packageManager: 'yarn@4.9.2',
    scripts: {
      'create-entity': 'twenty app add',
      dev: 'twenty app dev',
      generate: 'twenty app generate',
      sync: 'twenty app sync',
      logs: 'twenty app logs',
      uninstall: 'twenty app uninstall',
      help: 'twenty help',
      auth: 'twenty auth login',
    },
    dependencies: {
      'twenty-sdk': '0.2.0',
    },
    devDependencies: {
      '@types/node': '^24.7.2',
      typescript: '^5.9.3',
    },
  };

  await fs.writeFile(
    join(appDirectory, 'package.json'),
    JSON.stringify(packageJson, null, 2),
    'utf8',
  );
};
